package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserIdThreadLocal;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.entity.vo.OrderDto;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;



    //订单分页
    @Override
    public R pageOrders(Integer page, Integer pageSize) {
        //获取用户id
        Long userId = UserIdThreadLocal.getId();
        //获取订单
        Page<Orders> ordersPage = new Page<>();
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,userId);
        qw.orderByDesc(Orders::getOrderTime);
        ordersMapper.selectPage(ordersPage,qw);
        //获取当前订单
        List<Orders> orders = ordersPage.getRecords();
        ArrayList<OrderDto> orderDtos = new ArrayList<>();
        //获取订单详情，并封装进dto中
        for (Orders order : orders) {
            OrderDto orderDto = new OrderDto();
            //保存订单数据
            BeanUtil.copyProperties(order,orderDto);
            LambdaQueryWrapper<OrderDetail> orderdqw = new LambdaQueryWrapper<>();
            orderdqw.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(orderdqw);
            orderDto.setOrderDetails(orderDetails);
            orderDtos.add(orderDto);
        }
        HashMap<String, Object> map = new HashMap<>();
        //map里存dto
        map.put("total",ordersPage.getTotal());
        map.put("records", orderDtos);

        //ordersMapper.selectList(qw);
        //List<Orders> records = ordersPage.getRecords();
        return R.success(map);
    }
    //生成订单
    @Override
    public R submitOrders(Orders orders) {
        //获取用户id
        Long userId = UserIdThreadLocal.getId();
        //使用mp生成订单id(订单详情需要)
        long orderId = IdWorker.getId();

        //根据用户id获取购物车数据
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(qw);
        //新建总价容器
        BigDecimal bigDecimal = new BigDecimal(0);
        //遍历，收入订单明细
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart, orderDetail);
            //设置订单id
            orderDetail.setOrderId(orderId);
            //设置金额
            BigDecimal amount = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(amount.multiply(number));
           bigDecimal = bigDecimal.add(shoppingCart.getAmount());
            orderDetailMapper.insert(orderDetail);
        }
        //根据用户id获取用户数据
        LambdaQueryWrapper<User> userqw = new LambdaQueryWrapper<>();
        userqw.eq(User::getId,userId);
        User user = userMapper.selectOne(userqw);
        //根据地址id获取地址数据
        LambdaQueryWrapper<AddressBook> addqw = new LambdaQueryWrapper<>();
        addqw.eq(AddressBook::getId, orders.getAddressBookId());
        AddressBook addressBook = addressBookMapper.selectOne(addqw);
        //保存订单
        orders.setId(orderId);
        //保存订单号
        orders.setNumber(String.valueOf(orderId));
        //订单状态
        orders.setStatus(4);
        //保存下单用户id
        orders.setUserId(userId);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //实收金额
        orders.setAmount(bigDecimal);
        //用户名
        orders.setUserName(user.getName());
        //手机号
        orders.setPhone(addressBook.getPhone());
        //地址
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" :addressBook.getProvinceName())
                +(addressBook.getCityName() == null ? "" : addressBook.getCityName())
                +(addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                +addressBook.getDetail()
        );
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //保存
        ordersMapper.insert(orders);
        //清除购物车
        LambdaQueryWrapper<ShoppingCart> acqw = new LambdaQueryWrapper<>();
        acqw.eq(ShoppingCart::getUserId,userId);
        shoppingCartMapper.delete(acqw);
        return R.success("订单完成");
    }



}
